package com.atguigu.meinian.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.meinian.pojo.Permission;
import com.atguigu.meinian.pojo.Role;
import com.atguigu.meinian.pojo.User;
import com.atguigu.meinian.service.MemberService;
import com.atguigu.meinian.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author zbystart
 * @create 2021-06-25 19:19
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    /**
     * 完成登录认证，以及注册登录的用户权限
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 根据用户名获取用户信息
        User user = userService.queryUserAndRoleByUserName(userName);
        if (user == null) {
            return null;
        }

        // 根据用户id获取用户的角色列表
        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getKeyword());
                list.add(authority);
            }
        }
        // 注册
        return new org.springframework.security.core.userdetails.User(userName,user.getPassword(),list);
    }
}
